package cn.com.jrr.core.common;

import java.io.File;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.io.FileUtils;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.multipart.commons.CommonsMultipartResolver;

import cn.com.jrr.core.model.DataTableRequest;

public class ToolUtils {
    /**
     * 为hql语句拼接模糊查询及排序条件
     * */
    public static String SearchAndSortHql(String sql,DataTableRequest dataTableRequest,Object...params){
        StringBuffer sb=new StringBuffer("select * from("+sql+") t");
        String searchValue=dataTableRequest.getFuzzy();
        String orderColumn=dataTableRequest.getOrderColumn();
        String orderDir=dataTableRequest.getOrderDir();
        sql=sb.toString();
        if(dataTableRequest.isFuzzySearch()){
            if (params != null) {
                int len = params.length;
                if (len > 0) {
                    sb.append(" where ");
                    for (int i = 0; i < len; i++) {
                        sb.append("t."+params[i]+" like '%" + searchValue + "%' or ");
                    }
                    //去掉尾部的 " or "
                    sql=sb.substring(0,sb.length()-4);
                }
            }
        }
        if(orderColumn!=null){
            sql+=" order by t."+orderColumn+" "+orderDir;
        }
        return sql;
    }
    /**
     * 为hql语句拼接模糊查询
     * */
    public static String searchAndNoSortHql(String sql,String searchText,Object...params){
        StringBuffer sb=new StringBuffer("select * from("+sql+") t");
        sql=sb.toString();
        if(StringUtils.isBlank(searchText)){
            if (params != null) {
                int len = params.length;
                if (len > 0) {
                    sb.append(" where ");
                    for (int i = 0; i < len; i++) {
                        sb.append("t."+params[i]+" like '%" + searchText + "%' or ");
                    }
                    //去掉尾部的 " or "
                    sql=sb.substring(0,sb.length()-4);
                }
            }
        }
        return sql;
    }
    // 获取实体类的所有属性，返回Field数组
    /*Field[] field = pageModel.getClass().getDeclaredFields();
    for(int i=0;i<field.length;i++){
    	System.out.println(field[i].getName());
    	System.out.println(field[i].getGenericType().toString());
    }*/
    /**
     * 将多个ID拼接的字符串分隔为存放ID的LIST
     * */
    public static List<Integer> splitIdString(String idString){
        List<String> listString=Arrays.asList(idString.split(","));
        List<Integer> lsitInteger=new ArrayList<>();
        for(String l:listString){
            lsitInteger.add(Integer.parseInt(l));
        }

        return lsitInteger;
    }
    /**
     * 文件上传
     * 返回List<Map<String,Object>>数组
     * 		fileName:文件名称
     * 		fileSize:文件大小
     * 		...
     * @param request
     * @param targetPath 服务器文件存放路径(绝对路径)
     * */
    public static List<Map<String,Object>> uploadUtil(HttpServletRequest request,String targetPath){
        List<Map<String,Object>> list=new ArrayList<Map<String,Object>>();
        //将当前上下文初始化给  CommonsMutipartResolver （多部分解析器）
        CommonsMultipartResolver multipartResolver=new CommonsMultipartResolver(
                request.getSession().getServletContext());
        //检查form中是否有enctype="multipart/form-data"
        if(multipartResolver.isMultipart(request)){
            //将request变成多部分request
            MultipartHttpServletRequest multiRequest=(MultipartHttpServletRequest)request;
            //获取multiRequest 中所有的文件名
            @SuppressWarnings("rawtypes")
            Iterator iter=multiRequest.getFileNames();
            Map<String,Object> map;
            while(iter.hasNext()){
                //一次遍历所有文件
                MultipartFile file=multiRequest.getFile(iter.next().toString());
                if(file!=null){
                    map=new HashMap<String,Object>();
                    //上传
                    String OriginalFilename=file.getOriginalFilename();
                    String fileName=getDateStr("yyyyMMddHHmmss")+"."+getExtName(OriginalFilename);
                    try {
                        file.transferTo(new File(targetPath+"/"+fileName));
                        map.put("fileName", fileName);
                        map.put("fileSize", file.getSize());
                        list.add(map);
                    } catch (IllegalStateException e) {
                        e.printStackTrace();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }
            return list;
        }
        return null;
    }
    /**
     * 文件下载
     * @param path     文件绝对路径
     * @param fileName 文件名称
     * */
    public static ResponseEntity<byte[]> downloadUtil(String path,String fileName){
        File file=new File(path);
        HttpHeaders headers = new HttpHeaders();
        try {
            fileName = new String(fileName.getBytes("UTF-8"),"iso-8859-1");//为了解决中文名称乱码问题
            headers.setContentDispositionFormData("attachment", fileName);
            headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
            try {
                return new ResponseEntity<byte[]>(FileUtils.readFileToByteArray(file),
                        headers, HttpStatus.CREATED);
            } catch (IOException e) {
                e.printStackTrace();
            }
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        return null;
    }
    /**
     * 生成日期格式字符串
     * */
    public static String getDateStr(String format){
        Date date=new Date();
        SimpleDateFormat sdf=new SimpleDateFormat(format);
        return sdf.format(date)+String.valueOf(Math.round(Math.random()*1000));
    }
    /**
     * 获取文件后缀名
     * */
    public static String getExtName(String fileName){
        String[] token = fileName.split("\\.");
        String pf = token[1];
        return pf;
    }

}
